﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using System.Web;
using System.Reflection;
using System.DirectoryServices;

namespace SmartUPSHelperApp
{
    public partial class Form1 : Form
    {
        private RegistryKey myAPCAgentReg;
        private RegistryKey myRemoteRootKey;
        private string actServer;
        private string myAgentName;
        private bool updateReg;
        private bool updateAgent;
        private bool saveActions;
        private bool localAgent;
        private Assembly agentAssambly;
        private Type thisAgent;

        public Form1()
        {
            InitializeComponent();
            updateReg = false;
            saveActions = false;
            fillServerList();
            fillAgents();
            updateReg = true;
            saveActions = true;
        }

        private void fillServerList()
        {
            string myFQDN = System.Net.Dns.GetHostEntry("localhost").HostName;
            string myDomain = myFQDN.Substring(myFQDN.IndexOf(".")+1);
            updateAgent = false;
            DirectoryEntry entry = new DirectoryEntry("LDAP://"+myDomain);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            mySearcher.Filter = ("(objectClass=computer)");
            mySearcher.SizeLimit = int.MaxValue;
            mySearcher.PageSize = int.MaxValue;
            foreach (SearchResult resEnt in mySearcher.FindAll())
            {
                string thisComputerName = resEnt.GetDirectoryEntry().Name;
                if (thisComputerName.StartsWith("CN="))
                    thisComputerName = thisComputerName.Remove(0, 3);
                    cbServers.Items.Add(thisComputerName.ToLower());
            }
            mySearcher.Dispose();
            entry.Dispose();
            actServer = System.Net.Dns.GetHostName().ToLower();
            localAgent = true;
            button1.Text = "GetState && Save";
            updateAgent = true;
            cbServers.Text = System.Net.Dns.GetHostName();
        }

        private void fillAgents()
        {
            myAPCAgentReg = myRemoteRootKey.CreateSubKey("SOFTWARE\\MyUPSMonitor\\Agents");
            updateReg = false;
            cbAgentList.Items.Clear();
            foreach (string s in myAPCAgentReg.GetSubKeyNames())
            {
                cbAgentList.Items.Add(s);
            }
            if (cbAgentList.Items.Count > 0)
            {
                cbAgentList.SelectedIndex = 0;
            }
            updateReg = true;
        }

        private void cbAgentList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(myAgentName)) { saveActionGrid(myAgentName); }
            updateReg = false;
            myAPCAgentReg = myRemoteRootKey.CreateSubKey("SOFTWARE\\MyUPSMonitor\\Agents\\" + cbAgentList.Text);
            tbDLL.Text = "";
            tbAgantFactor.Text = "0";
            nurfon.Value = 0;
            nurof.Value = 0;
            try
            {
                tbDLL.Text = (string)myAPCAgentReg.GetValue("DLLPath");
                tbAgantFactor.Text = ((double)((Int32)myAPCAgentReg.GetValue("TimeFactor") / 1000)).ToString("#,##0.000");
                nurfon.Value = (int)myAPCAgentReg.GetValue("RefreshOnLine");
                nurof.Value = (int)myAPCAgentReg.GetValue("RefreshOffLine");
            }
            catch { }
            myAgentName = cbAgentList.Text;
            fillActionGrid(myAgentName);
            updateReg = true;
        }

        private void tbDLL_TextChanged(object sender, EventArgs e)
        {
            updateReg = false;
            cbClass.Items.Clear();
            cbfgmr.Items.Clear();
            cbfgs.Items.Clear();
            cbfiob.Items.Clear();
            try
            {
                agentAssambly = Assembly.LoadFile("\\\\" + actServer + "\\" + tbDLL.Text.Replace(":", "$"));
                foreach (Type t in agentAssambly.GetTypes()) cbClass.Items.Add(t.FullName);
                if (cbClass.Items.Count > 0) cbClass.SelectedIndex = 0;
                if (cbClass.Items.Contains((string)myAPCAgentReg.GetValue("AgentClass"))) cbClass.Text = (string)myAPCAgentReg.GetValue("AgentClass");
                thisAgent = agentAssambly.GetType(cbClass.Text);
                foreach (MethodInfo mi in thisAgent.GetMethods())
                {
                    cbfgmr.Items.Add(mi.Name);
                    cbfgs.Items.Add(mi.Name);
                    cbfiob.Items.Add(mi.Name);
                }
                if (cbfgmr.Items.Count > 0) cbfgmr.SelectedIndex = 0;
                if (cbfgs.Items.Count > 0) cbfgs.SelectedIndex = 0;
                if (cbfiob.Items.Count > 0) cbfiob.SelectedIndex = 0;
                if (cbfgmr.Items.Contains((string)myAPCAgentReg.GetValue("GetRemainingFunction"))) cbfgmr.Text = (string)myAPCAgentReg.GetValue("GetRemainingFunction");
                if (cbfgs.Items.Contains((string)myAPCAgentReg.GetValue("GetStatusFunction"))) cbfgs.Text = (string)myAPCAgentReg.GetValue("GetStatusFunction");
                if (cbfiob.Items.Contains((string)myAPCAgentReg.GetValue("IsOnBatteryFunction"))) cbfiob.Text = (string)myAPCAgentReg.GetValue("IsOnBatteryFunction");
            }
            catch { }
            updateReg = true;
        }

        private byte[] encryptPassword(string clearText)
        {
            byte[] salt ;
            string rst="";
            foreach (byte b in Encoding.ASCII.GetBytes(Convert.ToBase64String(Encoding.Unicode.GetBytes(clearText),Base64FormattingOptions.InsertLineBreaks)))
            {
                rst += ((uint)(b * b)).ToString("D5");
            }
            int i = 0;
            rst = Convert.ToBase64String(Encoding.ASCII.GetBytes(rst),Base64FormattingOptions.InsertLineBreaks);
            salt=new byte[rst.Length];
            foreach (byte b in Encoding.ASCII.GetBytes(rst))
            {
                salt[i++] = (byte)(255 - b);
            }
            return salt;
        }
        private string decryptPassword(byte[] encoded)
        {
            if (encoded == null )
            {
                return "";
            }
            string salt="" ;
            string rst="";
            foreach (byte b in encoded)
            {
                foreach (char c in Encoding.ASCII.GetChars(new byte[] { (byte)(255 - b) }))
                {
                    rst += c; 
                }
            }
            foreach (char c in Encoding.ASCII.GetChars(Convert.FromBase64String(rst)))
            {
                salt += c.ToString();
            }
            rst = "";
            for (int ii = 0; ii < salt.Length ; ii += 5)
            {
                rst += (char)Math.Sqrt(uint.Parse(salt.Substring(ii, 5)));
            }
            salt = "";
            foreach (char c in Encoding.Unicode.GetChars(Convert.FromBase64String(rst)))
            {
                salt += c.ToString();
            }
            return salt;
        }

        private void fillActionGrid(string myAgentName)
        {
            myAPCAgentReg = myRemoteRootKey.CreateSubKey("SOFTWARE\\MyUPSMonitor\\Agents\\" + myAgentName);
            RegistryKey actionsKey = myAPCAgentReg.CreateSubKey("Actions");
            RegistryKey actionKey;
            actionGrid.Rows.Clear();
            foreach (string actionName in actionsKey.GetSubKeyNames())
            {
                actionKey = actionsKey.OpenSubKey(actionName);
                actionGrid.Rows.Add(new object[] {actionName, (string)actionKey.GetValue("Type"),
                                                              (int)actionKey.GetValue("Down"),
                                                              (int)actionKey.GetValue("Up"),
                                                              (string)actionKey.GetValue("State"),
                                                              (string)actionKey.GetValue("HostName"),
                                                              (string)actionKey.GetValue("Service"),
                                                              actionKey.GetValue("TimeOut"),
                                                              (string)actionKey.GetValue("UserID"),
                                                              decryptPassword((byte[])actionKey.GetValue("Password"))});
            }
        }

        private void saveActionGrid(string myAgentName)
        {
            if (saveActions)
            {
                myAPCAgentReg = myRemoteRootKey.CreateSubKey("SOFTWARE\\MyUPSMonitor\\Agents\\" + myAgentName);
                if (myAPCAgentReg.GetSubKeyNames().Length == 0)
                {
                    myAPCAgentReg.CreateSubKey("Actions");
                }
                RegistryKey actionsKey = myAPCAgentReg.OpenSubKey("Actions", true);
                RegistryKey actionKey;
                int i;
                foreach (DataGridViewRow row in actionGrid.Rows)
                {
                    if (!string.IsNullOrEmpty((string)row.Cells[0].Value))
                    {
                        actionKey = actionsKey.CreateSubKey((string)row.Cells[0].Value, RegistryKeyPermissionCheck.ReadWriteSubTree);
                        actionKey.SetValue("Type", (string)row.Cells[1].Value);
                        if (row.Cells[2].Value != null) if (int.TryParse(row.Cells[2].Value.ToString(), out i)) { actionKey.SetValue("Down", i); }
                        if (row.Cells[3].Value != null) if (int.TryParse(row.Cells[3].Value.ToString(), out i)) { actionKey.SetValue("Up", i); }
                        if (!string.IsNullOrEmpty((string)row.Cells[5].Value)) { actionKey.SetValue("Hostname", (string)row.Cells[5].Value); }
                        if (!string.IsNullOrEmpty((string)row.Cells[6].Value)) { actionKey.SetValue("Service", (string)row.Cells[6].Value); }
                        if (row.Cells[7].Value != null) if (int.TryParse(row.Cells[7].Value.ToString(), out i)) { actionKey.SetValue("TimeOut", i); }
                        if (!string.IsNullOrEmpty((string)row.Cells[8].Value)) { actionKey.SetValue("UserID", (string)row.Cells[8].Value); }
                        if (!string.IsNullOrEmpty((string)row.Cells[9].Value)) { actionKey.SetValue("Password", encryptPassword((string)row.Cells[9].Value)); }
                    }
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            saveActionGrid(myAgentName);
        }

        private void cbfgmr_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool myupdatereg = updateReg;
            if (updateReg)
            {
                myAPCAgentReg.SetValue("GetRemainingFunction", cbfgmr.Text);
            }
            updateReg = false;
            dgvfgmr.Rows.Clear();
            foreach (ParameterInfo pi in thisAgent.GetMethod(cbfgmr.Text).GetParameters())
            {
                if (pi.Name == "Password")
                {
                    dgvfgmr.Rows.Add(new object[] { pi.Name, decryptPassword((byte[])myAPCAgentReg.GetValue(pi.Name)) });
                }
                else
                    dgvfgmr.Rows.Add(new object[] { pi.Name, myAPCAgentReg.GetValue(pi.Name) });
            }
            updateReg = myupdatereg;
        }

        private void cbfgs_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool myupdatereg = updateReg;
            if (updateReg)
            {
                myAPCAgentReg.SetValue("GetStatusFunction", cbfgs.Text);
            }
            updateReg = false;
            dgvfgs.Rows.Clear();
            foreach (ParameterInfo pi in thisAgent.GetMethod(cbfgs.Text).GetParameters())
            {
                if (pi.Name == "Password")
                {
                    dgvfgs.Rows.Add(new object[] { pi.Name, decryptPassword((byte[])myAPCAgentReg.GetValue(pi.Name)) });
                }
                else
                    dgvfgs.Rows.Add(new object[] { pi.Name, myAPCAgentReg.GetValue(pi.Name) });
            }
            updateReg = myupdatereg;
        }

        private void cbfiob_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool myupdatereg = updateReg;
            if (updateReg)
            {
                myAPCAgentReg.SetValue("IsOnBatteryFunction", cbfiob.Text);
            }
            updateReg = false;
            dgvfiob.Rows.Clear();
            foreach (ParameterInfo pi in thisAgent.GetMethod(cbfiob.Text).GetParameters())
            {
                if (pi.Name == "Password")
                {
                    dgvfiob.Rows.Add(new object[] { pi.Name, decryptPassword((byte[])myAPCAgentReg.GetValue(pi.Name)) });
                }
                else
                    dgvfiob.Rows.Add(new object[] { pi.Name, myAPCAgentReg.GetValue(pi.Name) });
            }
            updateReg = myupdatereg;
        }

        private object getParamValueByName(DataGridViewRowCollection myRows, string myParamName)
        {
            object myResult = null;
            foreach (DataGridViewRow myRow in myRows)
            {
                if (((string)myRow.Cells[0].Value).ToLower()==myParamName.ToLower())
                {
                    myResult = myRow.Cells[1].Value;
                }
            }
            return myResult;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool allOK = true;
            string myAgentName = cbAgentList.Text;
            string myStatus;
            bool onBattery;
            int upsRemaining;
            int rfon = (int)nurfon.Value;
            int rfoff = (int)nurof.Value;
            UInt32 upsFactor = (UInt32)(double.Parse(tbAgantFactor.Text)*1000);
            string agentDLL = tbDLL.Text;
            string agentClass = cbClass.Text;
            Assembly agentAssambly;
            Type thisAgent;
            string functionGetMinutesRemaining = cbfgmr.Text;
            object[] paramsForGetMinutesRemaining;
            string functionIsOnBattery = cbfiob.Text;
            object[] paramsForIsOnBattery;
            string functionGetStatus = cbfgs.Text;
            object[] paramsForGetStatus;
            ParameterInfo[] myParams;
            if (localAgent)
            {
                try
                {
                    agentAssambly = Assembly.LoadFile(agentDLL);
                    thisAgent = agentAssambly.GetType(agentClass, true, true);
                    myParams = ((MethodInfo)thisAgent.GetMember(functionGetMinutesRemaining)[0]).GetParameters();
                    paramsForGetMinutesRemaining = new object[myParams.Length];
                    for (int i = 0; i < myParams.Length; i++)
                    {
                        paramsForGetMinutesRemaining[i] = getParamValueByName(dgvfgmr.Rows, myParams[i].Name);
                    }
                    myParams = ((MethodInfo)thisAgent.GetMember(functionGetStatus)[0]).GetParameters();
                    paramsForGetStatus = new object[myParams.Length];
                    for (int i = 0; i < myParams.Length; i++)
                    {
                        paramsForGetStatus[i] = getParamValueByName(dgvfgs.Rows, myParams[i].Name);
                    }
                    myParams = ((MethodInfo)thisAgent.GetMember(functionIsOnBattery)[0]).GetParameters();
                    paramsForIsOnBattery = new object[myParams.Length];
                    for (int i = 0; i < myParams.Length; i++)
                    {
                        paramsForIsOnBattery[i] = getParamValueByName(dgvfiob.Rows, myParams[i].Name);
                    }
                    upsRemaining = (int)thisAgent.InvokeMember(functionGetMinutesRemaining, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, paramsForGetMinutesRemaining);
                    myStatus = (string)thisAgent.InvokeMember(functionGetStatus, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, paramsForGetStatus);
                    onBattery = (bool)thisAgent.InvokeMember(functionIsOnBattery, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, paramsForIsOnBattery);
                    lblfgmr.Text = "Get Remaining. Result is: " + upsRemaining.ToString("#,##0.00");
                    lblfgs.Text = "Get Status. Result is: " + myStatus;
                    lblfiob.Text = "Is On Battery. Result is: " + onBattery.ToString();
                }
                catch (Exception ex)
                {
                    lblfgmr.Text = "Get Remaining";
                    lblfgs.Text = "Get Status";
                    lblfiob.Text = "Is On Battery";
                    allOK = false;
                    MessageBox.Show("Exception thrown while querying the UPS:\r\n" + ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (allOK)
            {
                if (myAPCAgentReg.Name!="HKEY_LOCAL_MACHINE\\SOFTWARE\\MyUPSMonitor\\Agents\\"+myAgentName)
                {
                    myAPCAgentReg = RenameSubKey( myAPCAgentReg, myAgentName);
                }
                myAPCAgentReg.SetValue("AgentClass", agentClass);
                myAPCAgentReg.SetValue("DLLPath", agentDLL,RegistryValueKind.ExpandString);
                myAPCAgentReg.SetValue("GetRemainingFunction", functionGetMinutesRemaining);
                myAPCAgentReg.SetValue("GetStatusFunction", functionGetStatus);
                myAPCAgentReg.SetValue("IsOnBatteryFunction", functionIsOnBattery);
                myAPCAgentReg.SetValue("TimeFactor", upsFactor, RegistryValueKind.DWord);
                myAPCAgentReg.SetValue("RefreshOnLine", rfon, RegistryValueKind.DWord);
                myAPCAgentReg.SetValue("RefreshOffLine", rfoff, RegistryValueKind.DWord);
                foreach (DataGridViewRow myRow in dgvfgmr.Rows)
                {
                    if ((string)myRow.Cells[0].Value == "Password")
                    {
                        myAPCAgentReg.SetValue((string)myRow.Cells[0].Value, encryptPassword((string)myRow.Cells[1].Value));
                    }
                    else
                    {
                        myAPCAgentReg.SetValue((string)myRow.Cells[0].Value, (string)myRow.Cells[1].Value);
                    }
                }
            }
        }

        public bool RenameSubKey(RegistryKey parentKey, string subKeyName, string newSubKeyName)
        {
            CopyKey(parentKey, subKeyName, newSubKeyName);
            parentKey.DeleteSubKeyTree(subKeyName);
            return true;
        }

        public RegistryKey RenameSubKey(RegistryKey subKey, string newSubKeyName)
        {
            string oldkeyName = subKey.Name.Substring(subKey.Name.LastIndexOf("\\")+1);
            RegistryKey myRootKey = myRemoteRootKey.OpenSubKey(subKey.Name.Substring(19, subKey.Name.LastIndexOf("\\") - 19), true);
            CopyKey(myRootKey, oldkeyName, newSubKeyName);
            myRootKey.DeleteSubKeyTree(oldkeyName);
            return myRootKey.OpenSubKey(newSubKeyName,true);
        }

        public bool CopyKey(RegistryKey parentKey, string keyNameToCopy, string newKeyName)
        {
            RegistryKey destinationKey = parentKey.CreateSubKey(newKeyName);
            RegistryKey sourceKey = parentKey.OpenSubKey(keyNameToCopy);
            RecurseCopyKey(sourceKey, destinationKey);
            return true;
        }

        private void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey)
        {
            foreach (string valueName in sourceKey.GetValueNames())
            {
                object objValue = sourceKey.GetValue(valueName);
                RegistryValueKind valKind = sourceKey.GetValueKind(valueName);
                destinationKey.SetValue(valueName, objValue, valKind);
            }
            foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames())
            {
                RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName);
                RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName);
                RecurseCopyKey(sourceSubKey, destSubKey);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bool allOK = true;
            string myAgentName = cbAgentList.Text;
            string myStatus;
            bool onBattery;
            int upsRemaining;
            int rfon = (int)nurfon.Value;
            int rfoff = (int)nurof.Value;
            UInt32 upsFactor = (UInt32)(double.Parse(tbAgantFactor.Text) * 1000);
            string agentDLL = tbDLL.Text;
            string agentClass = cbClass.Text;
            Assembly agentAssambly;
            Type thisAgent;
            string functionGetMinutesRemaining = cbfgmr.Text;
            object[] paramsForGetMinutesRemaining;
            string functionIsOnBattery = cbfiob.Text;
            object[] paramsForIsOnBattery;
            string functionGetStatus = cbfgs.Text;
            object[] paramsForGetStatus;
            ParameterInfo[] myParams;
            if (localAgent)
            {
                try
                {
                    agentAssambly = Assembly.LoadFile(agentDLL);
                    thisAgent = agentAssambly.GetType(agentClass, true, true);
                    myParams = ((MethodInfo)thisAgent.GetMember(functionGetMinutesRemaining)[0]).GetParameters();
                    paramsForGetMinutesRemaining = new object[myParams.Length];
                    for (int i = 0; i < myParams.Length; i++)
                    {
                        paramsForGetMinutesRemaining[i] = getParamValueByName(dgvfgmr.Rows, myParams[i].Name);
                    }
                    myParams = ((MethodInfo)thisAgent.GetMember(functionGetStatus)[0]).GetParameters();
                    paramsForGetStatus = new object[myParams.Length];
                    for (int i = 0; i < myParams.Length; i++)
                    {
                        paramsForGetStatus[i] = getParamValueByName(dgvfgs.Rows, myParams[i].Name);
                    }
                    myParams = ((MethodInfo)thisAgent.GetMember(functionIsOnBattery)[0]).GetParameters();
                    paramsForIsOnBattery = new object[myParams.Length];
                    for (int i = 0; i < myParams.Length; i++)
                    {
                        paramsForIsOnBattery[i] = getParamValueByName(dgvfiob.Rows, myParams[i].Name);
                    }
                    upsRemaining = (int)thisAgent.InvokeMember(functionGetMinutesRemaining, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, paramsForGetMinutesRemaining);
                    myStatus = (string)thisAgent.InvokeMember(functionGetStatus, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, paramsForGetStatus);
                    onBattery = (bool)thisAgent.InvokeMember(functionIsOnBattery, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, paramsForIsOnBattery);
                    lblfgmr.Text = "Get Remaining. Result is: " + upsRemaining.ToString("#,##0.00");
                    lblfgs.Text = "Get Status. Result is: " + myStatus;
                    lblfiob.Text = "Is On Battery. Result is: " + onBattery.ToString();
                }
                catch (Exception ex)
                {
                    lblfgmr.Text = "Get Remaining";
                    lblfgs.Text = "Get Status";
                    lblfiob.Text = "Is On Battery";
                    allOK = false;
                    MessageBox.Show("Exception thrown while querying the UPS:\r\n" + ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (allOK)
            {
                if (myAPCAgentReg.Name != "HKEY_LOCAL_MACHINE\\SOFTWARE\\MyUPSMonitor\\Agents\\" + myAgentName)
                {
                    myAPCAgentReg = myRemoteRootKey.CreateSubKey("SOFTWARE\\MyUPSMonitor\\Agents\\" + myAgentName);
                }
                myAPCAgentReg.SetValue("AgentClass", agentClass);
                myAPCAgentReg.SetValue("DLLPath", agentDLL, RegistryValueKind.ExpandString);
                myAPCAgentReg.SetValue("GetRemainingFunction", functionGetMinutesRemaining);
                myAPCAgentReg.SetValue("GetStatusFunction", functionGetStatus);
                myAPCAgentReg.SetValue("IsOnBatteryFunction", functionIsOnBattery);
                myAPCAgentReg.SetValue("TimeFactor", upsFactor, RegistryValueKind.DWord);
                myAPCAgentReg.SetValue("RefreshOnLine", rfon, RegistryValueKind.DWord);
                myAPCAgentReg.SetValue("RefreshOffLine", rfoff, RegistryValueKind.DWord);
                foreach (DataGridViewRow myRow in dgvfgmr.Rows)
                {
                    if ((string)myRow.Cells[0].Value == "Password")
                    {
                        myAPCAgentReg.SetValue((string)myRow.Cells[0].Value, encryptPassword((string)myRow.Cells[1].Value));
                    }
                    else
                    {
                        myAPCAgentReg.SetValue((string)myRow.Cells[0].Value, (string)myRow.Cells[1].Value);
                    }
                }
                updateReg = false;
                fillAgents();
                updateReg = true;
            }
        }

        private void cbServers_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (updateAgent)
                {
                    myRemoteRootKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, cbServers.Text);
                    actServer = cbServers.Text.ToLower();
                    if (actServer.ToLower() == System.Net.Dns.GetHostName().ToLower())
                    {
                        localAgent = true;
                        button1.Text = "GetState && Save";
                    }
                    else
                    {
                        localAgent = false;
                        button1.Text = "Save wo test";
                    }
                    updateReg = false;
                    saveActions = false;
                    fillAgents();
                    updateReg = true;
                    saveActions = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured connecting to \"" + cbServers.Text + "\": \r\n" + ex.Message, "Error", MessageBoxButtons.OK);
                updateAgent = true;
                cbServers.Text = actServer.ToLower();
                updateAgent = true;
            }
        }


    }
}
